import java.net.*;
import java.io.*;
import java.util.*;

public class test1 {
	private URL source;
	private String sessionid;
	private String cookieval;
	private String token;
	private String username;
	private String password;
	private static final String folderinfo = "http://software.nju.edu.cn:8000/cgi-bin/disp_folder_info?uid=";
	private static final String listmail = "http://software.nju.edu.cn:8000/cgi-bin/listmail?folder=Inbox&search=no&sort=dtr&pg=";
	//private static final String readbody = "http://software.nju.edu.cn:8000/cgi-bin/readbody?";
	private ArrayList<mail> emails = new ArrayList<mail>();

	public static void main(String[] args) {
		try {
			test1 test = new test1();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			System.err.print("Username: ");
			test.username = br.readLine();
			System.err.print("Password: ");
			test.password = br.readLine();
			// test.get();
			test.post();
			test.post2();
			test.post3();
			test.listfolder();
			test.listmail();
		} catch (IOException ex) {
			System.err.println("A system or network error has occured");
			System.exit(1);
		}
	}

	private void post() throws IOException { // Initial attempt: Get cookie
		source = new URL("http://software.nju.edu.cn:8000/cgi-bin/login");
		HttpURLConnection conn = (HttpURLConnection) source.openConnection();
		conn.setRequestMethod("POST");   //Make a POST request
		conn.setDoOutput(true);
		StringBuffer buf = new StringBuffer();
		buf.append("LoginName=" + this.username + "@software.nju.edu.cn");
		buf.append("&Password=" + this.password);
		OutputStream os = conn.getOutputStream();
		os.write(buf.toString().getBytes());
		os.close();
		conn.connect();
		// System.err.println(conn.getResponseCode());
		cookieval = conn.getHeaderField("Set-Cookie"); //Store cookie
		sessionid = "";
		if (cookieval != "")
			sessionid = cookieval.substring(0, cookieval.indexOf(";"));
	}

	private void post2() throws IOException { // Second attempt: Get token
		HttpURLConnection conn = (HttpURLConnection) source.openConnection();
		if (sessionid != "")
			conn.setRequestProperty("Cookie", sessionid);
		conn.connect();
		/*
		 * String cookieval = conn.getHeaderField("Set-Cookie"); String
		 * sessionid = ""; if (cookieval != null) { if (!cookieval.equals("")) {
		 * sessionid = cookieval.substring(0, cookieval.indexOf(";"));
		 * this.cookieval = cookieval; this.sessionid = sessionid; } }
		 */
		// System.err.println(conn.getResponseMessage());
		BufferedReader br = new BufferedReader(new InputStreamReader(conn
				.getInputStream(), "GBK"));
		String cur = br.readLine();
		while (cur != null) {
			if (cur.contains("token=")) {  //Validates if logged in correctly or not
				this.token = cur.substring(7, cur.length() - 2);
				break;
			}
			cur = br.readLine();
		}
		if (token == null) { //If not logged in, exits
			System.err.println("Invaild username or password");
			System.exit(1);
		}
	}

	private void post3() throws IOException { // The real process
		source = new URL(
				"http://software.nju.edu.cn:8000/cgi-bin/login?token=" + token);
		HttpURLConnection conn = (HttpURLConnection) source.openConnection();
		if (sessionid != "")
			conn.setRequestProperty("Cookie", sessionid);
		conn.setRequestProperty("Referer",
				"http://software.nju.edu.cn:8000/cgi-bin/login?token=" + token);
		conn.connect();
		// System.err.println(conn.getResponseMessage());
	}

	private void listfolder() throws IOException {
		int total = 0, unread = 0;
		URL url = new URL(folderinfo + this.username
				+ "&domain=software.nju.edu.cn");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestProperty("Cookie", this.sessionid);
		conn.connect();
		InputStream stream = conn.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(stream));
		String cur = "";
		boolean totalf = false;
		while (br.ready()) {
			cur = br.readLine();
			if (cur.contains("tblcautionfont")) { //Header of each folder's HTML
				//TODO Need expansion; this is limited to "Inbox" only
				if (!totalf) {
					totalf = true;
					total = Integer.parseInt(cur.split("<")[1].substring(28,
							cur.split("<")[1].length()));
				} else {
					unread = Integer.parseInt(cur.split("<")[1].substring(29,
							cur.split("<")[1].length()));
				}
			}
		}
		System.out.println("Total: " + total);
		System.out.println("Unread: " + unread);
	}

	private void listmail() throws IOException {
		URL url = new URL(listmail + "0"); // TODO Multiple pages support needed
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestProperty("Cookie", this.sessionid);
		conn.connect();
		InputStream stream = conn.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(stream,"GBK"));
		String cur = "";
		boolean incell = false;
		boolean hasattachment=false;
		String curID = "";
		String curtitle = "";
		String cursender = "";
		String curdate = "";
		while (br.ready()) {  //Identify the identifiers of each line and seek for useful information
			cur = br.readLine();
			if (cur.contains("libtblnormalcellbg") || cur.contains("libtblleft1cellbg"))   //At the head of each mail
				incell = true;
			if (incell) {
				if (cur.contains("MSG.")) {   //Message number - will be used when retrieving contents
					curID = cur.split("value=")[1].substring(1, cur
							.split("value=")[1].length() - 2);
					continue;
				}
				if (cur.contains("32%")) {  //Sender of this particular email
					cursender = cur.split(">")[2].substring(0,
							cur.split(">")[2].length() - 3);
					cursender=process(cursender);
					continue;
				}
				if (cur.contains("14%")) {  //Date sent
					curdate = cur.split(">")[1].substring(0, cur.split(">")[1]
							.length() - 4);
					curdate=process(curdate);
					continue;
				}
				if (cur.contains("33%")) { //Mail's subject
					curtitle = cur.substring(16,cur.length()-4);
					curtitle=process(curtitle);
					continue;
				}
				if (cur.contains("9%")){
					if(cur.contains("attachsign.gif"))hasattachment=true;
					mail curmail = new mail(cursender, curtitle, curdate,hasattachment);
					curmail.setID(curID);
					this.emails.add(curmail);  //All information has been gathered, to next one
					incell = false;
					curID = "";
					curtitle = "";
					cursender = "";
					curdate = "";
					hasattachment=false;
					continue;
				}
			}
		}
		for(int i=0;i<this.emails.size();i++)
			System.out.println(emails.get(i).toString());
	}

	private String process(String str){   //TODO Need expansion
		String tobereturned=str.replace("&nbsp;"," ");
		tobereturned = tobereturned.replace("&lt;", "<");
		tobereturned = tobereturned.replace("&gt;", ">");
		tobereturned = tobereturned.replace("&quot;","");
		return tobereturned;
	}
}
